package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;
import static com.jspgou.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jspgou.cms.entity.Order;
import com.jspgou.cms.entity.OrderItem;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ProductFashion;
import com.jspgou.cms.entity.Shipments;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.ShopScore;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.DiscussMng;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.OrderReturnMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ProductFashionMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ShipmentsMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.manager.ShopMemberMng;
import com.jspgou.cms.manager.ShopScoreMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.cms.web.threadvariable.MemberThread;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;
import com.jspgou.core.web.front.URLHelper;

@Controller
public class OrderStFroAct {
	private static final Logger log=LoggerFactory.getLogger(OrderStFroAct.class);
    /**
     * 店铺订单列表页
    */
    public static final String TPL_ORDER_STORE_LIST = "tpl.orderStoreList";
	/**
	 * 店铺订单详情页
	 */
	private static final String TPL_ORDER_STORE_VIEW = "tpl.orderStoreView";
	/**
	 * 店铺订单修改页
	 */
	public static final String  TPL_ORDER_STORE_EDIT="tpl.orderStoreEdit";
    /**
     * 店铺发货订单列表页
    */
    public static final String TPL_ORDER_DELIVER_STORE_LIST = "tpl.orderDeliverStoreList";
    /**
     * 店铺发货页
    */
    public static final String TPL_ORDER_STORE_DELIVER = "tpl.orderStoreDeliver";
    /**
     * 店铺退货页
     */
    public static final String TPL_RETURN_ORDER="tpl.returnOrder";
    /**
     * 店铺订单退货详情页
     */
    public static final String TPL_RETURN_ORDER_VIEW="tpl.returnOrderView";
    //打印订单页
    public static final String TPL_PRINT_ORDER = "tpl.printOrder";
    
    
	
    //订单列表
    /**
     * 
     * @param cl
     * @param paymentId  支付方式id
     * @param shippingId 配送方式id
     * @param status  订单状态
     * @param productName 商品名称 
     * @param paymentStatus 支付状态
     * @param shippingStatus 配送状态
     * @param userName 收货人
     * @param startTime 下单时间
     * @param endTime
     * @param startOrderTotal 订单金额
     * @param endOrderTotal
     * @param request
     * @param model
     * @return
     */
	@RequestMapping(value = "/orderSt/list*.jspx")
	public String myOrder(String cl,Long paymentId,Long shippingId,String code,Integer status,Boolean isRefunded,String productName,
			Integer paymentStatus,Integer shippingStatus,String userName, String startTime,String endTime,
			Double startOrderTotal,Double endOrderTotal,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("shippingList", shippingList);
		model.addAttribute("store", store);
		model.addAttribute("status", status);
		model.addAttribute("productName", productName);
		model.addAttribute("paymentStatus", paymentStatus);
		model.addAttribute("shippingStatus", shippingStatus);
		if(StringUtils.isBlank(userName)){
			model.addAttribute("userName", null);
		}else{
		  model.addAttribute("userName", userName);
		}
		if(StringUtils.isBlank(code)){
			model.addAttribute("code", null);
		}else{
		  model.addAttribute("code", code);
		}
		if(StringUtils.isBlank(startTime)){
			model.addAttribute("startTime", null);
		}else{
		  model.addAttribute("startTime", startTime);
		}
		if(StringUtils.isBlank(endTime)){
			model.addAttribute("endTime", null);
		}else{
		  model.addAttribute("endTime", endTime);
		}
		model.addAttribute("cl", cl);
		model.addAttribute("isRefunded", isRefunded);
		model.addAttribute("paymentId", paymentId);
		model.addAttribute("shippingId", shippingId);
		model.addAttribute("startOrderTotal",startOrderTotal);
		model.addAttribute("endOrderTotal", endOrderTotal);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_ORDER_STORE_LIST), request);
	}
	
	/**
	 * 打印订单
	 * @param ids 订单ID
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/orderSt/printOrder.jspx")
	public String printOrder(Long[] ids,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		List<Order> orders = new ArrayList<Order>();
		for (int i = 0; i < ids.length; i++) {
			orders.add(manager.findById(ids[i]));
		}
		model.addAttribute("count", orders.size()-1);
		model.addAttribute("orders", orders);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_PRINT_ORDER), request);
	}
	
	//发货订单列表页
	@RequestMapping(value = "/orderSt/deliverList*.jspx")
	public String deliverList(String cl,Integer pageNo,Long paymentId,Long shippingId,Integer status,String productName,
			String userName, String startTime,String endTime,Double startOrderTotal,
			Double endOrderTotal,HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
 		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
 		//Pagination pagination = shipmentMng.getFcList(memberId,cpn(pageNo),CookieUtils.getPageSize(request));
		//支付方式
 		//model.addAttribute("pagination", pagination);
 		model.addAttribute("pageNo", pageNo);
		model.addAttribute("paymentList", paymentList);
		if(StringUtils.isBlank(userName)){
			model.addAttribute("userName", null);
		}else{
		  model.addAttribute("userName", userName);
		}
		if(StringUtils.isBlank(startTime)){
			model.addAttribute("startTime", null);
		}else{
		  model.addAttribute("startTime", startTime);
		}
		if(StringUtils.isBlank(endTime)){
			model.addAttribute("endTime", null);
		}else{
		  model.addAttribute("endTime", endTime);
		}
		model.addAttribute("cl", cl);
		model.addAttribute("store", store);
		model.addAttribute("paymentId", paymentId);
		model.addAttribute("startOrderTotal",startOrderTotal);
		model.addAttribute("endOrderTotal", endOrderTotal);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_ORDER_DELIVER_STORE_LIST), request);
	}
	
	//退货订单列表页
	@RequestMapping(value ="/orderSt/returnList.jspx")
	public String returnList(String cl,Integer status,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		//Pagination pagination=manager.getFcPage(web.getId(), status, storeId, member.getId(), pageNo, 15);
		//model.addAttribute("pagination", pagination);
		model.addAttribute("cl", cl);
		model.addAttribute("status", status);
		model.addAttribute("store", store);
		model.addAttribute("member", member);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_RETURN_ORDER), request);
	}
	
	//退货订单详情页
	@RequestMapping(value="/orderSt/returnListView.jspx")
	public String returnListView(Long returnId,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors = validateOrderView(returnId, member, request);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		model.addAttribute("order", manager.findById(returnId));
		model.addAttribute("orderReturn", orderReturnMng.findByOrderId(returnId));
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_RETURN_ORDER_VIEW), request);
	}
	
	//查看订单详情
	@RequestMapping(value = "/orderSt/view.jspx")
	public String myOrderView(Long orderId, HttpServletRequest request,Integer op,Integer pageNo,boolean param,
			ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors = validateOrderView(orderId, member, request);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		Order order = manager.findById(orderId);
		model.addAttribute("op",op);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("order", order);
		model.addAttribute("orderReturn", orderReturnMng.findByOrderId(orderId));
		model.addAttribute("param", param);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				TPL_ORDER_STORE_VIEW), request);
	}
	//点击确认按钮
	@RequestMapping(value="/orderSt/o_affirm.jspx")
	public String affirm(Long id,HttpServletRequest request,ModelMap model,Integer op,
			Integer pageNo,boolean param){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Order order=manager.findById(id);
		if(order.getStatus()==1){
			order.setStatus(2);
			manager.updateByUpdater(order);
		}
		model.addAttribute("order", order);
		model.addAttribute("op",op);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("param", param);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				TPL_ORDER_STORE_VIEW), request);
	}
	
	//完成按钮
	@RequestMapping("/orderSt/o_accomplish.jspx")
	public String accomplist(Long id,HttpServletRequest request,ModelMap model,Integer op,
			Integer pageNo,boolean param){
		Website web=SiteUtils.getWeb(request);
		ShopMember member1=CmsUtils.getMember(request);
		if(member1==null){
			return "redirect:../login.jspx";
		}
		Order order=manager.findById(id);
		if(order.getShippingStatus()==2&&order.getStatus()==2&&order.getPaymentStatus()==2){
			//修改订单的状态
			order.setStatus(4);
			//会员冻结的积分
			ShopMember member=order.getMember();
			//冻结的积分清除掉
			member.setFreezeScore(member.getFreezeScore()-order.getScore());
			//会员的积分相应的增加
			member.setScore(member.getScore()+order.getScore());
			shopMemberMng.update(member);
			List<ShopScore> list=shopScoreMng.getlist(order.getCode());
			for(ShopScore s:list){
				s.setStatus(true);
				shopScoreMng.update(s);
			}
			manager.updateByUpdater(order);
		}
		model.addAttribute("order", order);
		model.addAttribute("op", op);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("param", param);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				TPL_ORDER_STORE_VIEW), request);
	}
	
	//取消按钮
	@RequestMapping("/orderSt/o_abolish.jspx")
	public String abolish(Long id,HttpServletRequest request,ModelMap model,Integer op,
			Integer pageNo,boolean param){
		Website web=SiteUtils.getWeb(request);
		ShopMember member1=CmsUtils.getMember(request);
		if(member1==null){
			return "redirect:../login.jspx";
		}
		Order order=manager.findById(id);
		if(order.getStatus()!=4&&order.getShippingStatus()!=2&&order.getPaymentStatus()!=2){
			order.setStatus(3);
			//处理库存，OrderItem订单项
			for(OrderItem item:order.getItems()){
				//找出哪些商品
				Product product=item.getProduct();
				//如果商品款式外键不为空
				if(item.getProductFash()!=null){
					ProductFashion fashion=item.getProductFash();
					//款式库存增加
					fashion.setStockCount(fashion.getStockCount()+item.getCount());
					//商品库存增加
					product.setStockCount(product.getStockCount()+item.getCount());
					productFashionMng.update(fashion);
				}else{
					product.setStockCount(product.getStockCount()+item.getCount());
				}
				productMng.update(product);
			}
			//会员冻结的积分
			//获取会员
			ShopMember member=order.getMember();
			//把会员购买的商品获得积分减掉
			member.setFreezeScore(member.getFreezeScore()-order.getScore());
			shopMemberMng.update(member);
			//积分明细类ShopScore
			List<ShopScore> list=shopScoreMng.getlist(order.getCode());
			for(ShopScore s:list){
				shopScoreMng.deleteById(s.getId());
			}
			manager.updateByUpdater(order);
		}
		model.addAttribute("order", order);
		model.addAttribute("op", op);
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("param", param);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
				TPL_ORDER_STORE_VIEW), request);
	}
	
	//订单删除
	@RequestMapping(value="/orderSt/delete.jspx")
	public String delete(Long[] orderId,HttpServletRequest request,ModelMap model,Integer pageNo){
		Order[] beans;
		try{
			beans=manager.deleteByIds(orderId);
			for(Order bean :beans){
				log.info("delete Order id={}", bean.getId());
			}
		}catch(Exception e){	
		}
		return "redirect:list.jspx";		
	}		
	
	//点击发货按钮
	@RequestMapping(value="/orderSt/v_sendGoods.jspx")
	public String sendGoods(Long id, HttpServletRequest request, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Order order=manager.findById(id);
		model.addAttribute("order", order);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_ORDER_STORE_DELIVER), request);
	}
	
	//修改订单按钮
	@RequestMapping(value="/orderSt/editButton.jspx")
	public String edit(Long orderId,HttpServletRequest request,Integer pageNo,
			HttpServletResponse response,ModelMap model) {
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Order order=manager.findById(orderId);
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		model.addAttribute("shippingList", shippingList);
		model.addAttribute("order",order);
		model.addAttribute("pageNo",pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_ORDER_STORE_EDIT), request);
	}
	
	/**
	 * 前台店铺订单修改
	 * @param id 订单id
	 * @param freight 运费
	 * @param shippingId 配送方式id
	 * @param itemId 商品id
	 * @param itemCount 每件商品所购数量
	 * @param itemPrice 每件商品单价
	 * @param totalPrice 商品总价格
	 * @param pageNo 
	 * @param request 
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/orderSt/editOrder.jspx")
	public String editOrder(Long id,Double freight,Long shippingId,Long[] itemId,
			Integer[] itemCount,Double[] itemPrice,Double totalPrice,Integer pageNo,
			HttpServletRequest request,ModelMap model){
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		WebErrors errors=validateUpdate(id,freight,shippingId,itemId,itemCount,itemPrice,request);
		if(errors.hasErrors()){
			return errors.showErrorPage(model);
		}
		Order order=manager.findById(id);
		Store store=member.getStore();
		Set<OrderItem> items=order.getItems();
		Set<OrderItem> newItems=new HashSet<OrderItem>();
		Integer i;
		for(OrderItem item:items){
			i=findItem(itemId,item.getId());
			if(i!=null){
				if(itemCount[i]<=0){
					continue;
				}
				//修改后的商品单价
				item.setSalePrice(itemPrice[i]);
				//修改后的商品数量
				item.setCount(itemCount[i]);
				newItems.add(item);
			}
		}
		//清除订单项
		order.getItems().clear();
		for(OrderItem item:newItems){
			//加入修改后的订单项
			order.addToItems(item);
		}
		Double total=freight+totalPrice;
		//把修改后的运费传进去
		order.setFreight(freight);
		//把修改后的商品总价格传进去
		order.setProductPrice(totalPrice);
		//修改后的订单总额
		order.setTotal(total);
		//把修改后的配送方式传进去
		order.setShipping(shippingMng.findById(shippingId));
		order.setLastModified(new Timestamp(System.currentTimeMillis()));
		manager.updateByUpdater(order);
		log.info("update Order, id={}.", order.getId());
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("store", store);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("shippingList", shippingList);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		//return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_ORDER_STORE_LIST));
		return "redirect:list.jspx";
	}
	
	//修改订单
	@RequestMapping(value = "/orderSt/edit.jspx")
	public void editOrder(Long orderId,Integer status,HttpServletRequest request,
			HttpServletResponse response) throws JSONException {
		ShopMember member=CmsUtils.getMember(request);
		JSONObject json=new JSONObject();
		Order order=manager.findById(orderId);
		Product product=null;
		ShopScore shopScore=null;
		ProductFashion fashion=null;
		order.setStatus(status);
		order=manager.updateByUpdater(order);
		json.put("success", true);
		ResponseUtils.renderJson(response, json.toString());
	}
	
	private Integer findItem(Long[] itemIds,Long itemId){
		for(int i=0;i<itemIds.length;i++){
			if(itemIds[i].equals(itemId)){
				return i;
			}
		}
		return null;
	}
	
	private WebErrors validateUpdate(Long id,Double freight,Long shippingId,Long[] itemId,
			Integer[] itemCount,Double[] itemPrice,HttpServletRequest request){
		WebErrors errors=WebErrors.create(request);
		Website web=SiteUtils.getWeb(request);
		if(vldExist(id,web.getId(),errors)){
			return errors;
		}
		if(itemId==null||itemCount==null||itemPrice==null||itemId.length==0
				||itemId.length!=itemCount.length||itemCount.length!=itemPrice.length){
			errors.addErrorString("order item invalid!");
			return errors;
		}
		return errors;
	}
	
	private boolean vldExist(Long id,Long webId,WebErrors errors){
		if(errors.ifNull(id, "id")){
			return true;
		}
		Order entity=manager.findById(id);
		if(errors.ifNotExist(entity, Order.class, id)){
			return true;
		}
		if(!entity.getWebsite().getId().equals(webId)){
			errors.notInWeb(Order.class, id);
			return true;
		}
		return false;
	}
	
	private WebErrors validateOrderView(Long orderId, ShopMember member,
			HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNull(orderId, "orderId")) {
			return errors;
		}
		Order order = manager.findById(orderId);
		if (errors.ifNotExist(order, Order.class, orderId)) {
			return errors;
		}
		if (!member.getStore().getId().equals(order.getStore().getId())) {
 			errors.noPermission(Order.class, orderId);
 			return errors;
 		}
		return errors;
	}
	
	@Autowired
	private OrderMng manager;
	@Autowired
	private DiscussMng discussMng;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private ShippingMng shippingMng;
	@Autowired
	private ShopScoreMng shopScoreMng;
	@Autowired
	private ShopMemberMng shopMemberMng;
	@Autowired
	private ProductFashionMng productFashionMng;
	@Autowired
	private OrderReturnMng orderReturnMng;
	@Autowired
	private ShipmentsMng shipmentMng;

}
